package com.eh.statistics.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eh.commonutils.R;
import com.eh.statistics.client.UcenterClient;
import com.eh.statistics.entity.StatisticsDaily;
import com.eh.statistics.mapper.StatisticsDailyMapper;
import com.eh.statistics.service.StatisticsDailyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 网站统计日数据 服务实现类
 * </p>
 *
 * @author erhuo
 * @since 2021-01-22
 */
@Service
public class StatisticsDailyServiceImpl extends ServiceImpl<StatisticsDailyMapper, StatisticsDaily> implements StatisticsDailyService {

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public void registerCount(String day) {
        //添加记录之前删除表相同日期的数据
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.eq("date_calculated",day);
        baseMapper.delete(wrapper);

        R registerR = ucenterClient.getRegister(day);
        Integer countRegister = (Integer) registerR.getData().get("countRegister");
        //把获取数据添加数据库，统计分析表里面
        StatisticsDaily sta = new StatisticsDaily();
        sta.setRegisterNum(countRegister); //注册人数
        sta.setDateCalculated(day);//统计日期

        sta.setMessageNum(RandomUtils.nextInt(100,200));
        sta.setLoginNum(RandomUtils.nextInt(100,200));
        sta.setQuestionViewNum(RandomUtils.nextInt(100,200));
        baseMapper.insert(sta);
    }

    @Override
    public Map<String, Object> getShowData(String type, String begin, String end) {
        // 根据条件查询对应数据
        HashMap<String, Object> result = new HashMap<>();
        QueryWrapper<StatisticsDaily> wrapper = new QueryWrapper<>();
        wrapper.between("date_calculated", begin, end);
        wrapper.select("date_calculated", type); // 选择查询的字段
        List<StatisticsDaily> staList = baseMapper.selectList(wrapper);
        // 返回有两部分数据 ：日期 日期对应的数量
        // 前端要求数据JSON结构，前端数组对应后端Java代码list集合
        ArrayList<String> dateList = new ArrayList<>();
        ArrayList<Integer> numList = new ArrayList<>();
        for (StatisticsDaily daily : staList) {
            dateList.add(daily.getDateCalculated());
            if (type.equals("login_num")) {
                numList.add(daily.getLoginNum());
            } else if (type.equals("register_num")) {
                numList.add(daily.getRegisterNum());
            } else if (type.equals("question_view_num")) {
                numList.add(daily.getQuestionViewNum());
            } else {
                numList.add(daily.getMessageNum());
            }
        }
        result.put("dateList", dateList);
        result.put("numList", numList);
        return result;
    }
}
